var express = require('express');
var router = express.Router();
const UserModel = require('../../models/UserModel')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const {secret} = require('../../config/config')
// console.log(secret);

// 登录提交
router.post('/login', async (req, res) => {
    const {username, password} = req.body
    try {
       const data = await UserModel.findOne({username: username, password: md5(password)})
       console.log(data);
       if (!data) {
       return res.json({
            code: '2002',
            msg: '账号或密码错误',
            data: null
        })
       }
    
    // 创建用户当前的token
    const token = jwt.sign({
        username: data.username,
        _id: data._id
    }, secret, {
        expiresIn: 60 * 60 * 24 * 7
    })
    // 响应token
    res.json({
        code: '0000',
        msg: '登陆成功',
        data: token
    })
    } catch (error) { 
        res.json({
            code: '2001',
            msg: '数据库读取失败',
            data: null
        })
    }
})

// 退出登录
router.post('/logout', (req, res) => {
    req.session.destroy(() => {
        res.render('success', {msg: '推出成功', url: '/login'})
    })
    
})


module.exports = router;
